package com.zheng.provider.handler;

import com.zheng.provider.context.RpcContext;
import com.zheng.request.RpcRequest;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.lang.reflect.Method;

/**
 *  @author: zheng
 *  @Date: 2020-06-28 22:11
 *  @Description:自定义业务处理器
 */
public class UserServiceHandler extends ChannelInboundHandlerAdapter {

    //当客户端读取数据的时候会调用
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {

        if(msg instanceof RpcRequest){
            RpcRequest rpcRequest=(RpcRequest) msg;
            String className=rpcRequest.getClassName();
            String methodName=rpcRequest.getMethodName();
            Class<?>[] parameterTypes=rpcRequest.getParameterTypes();
            Object [] parameters=rpcRequest.getParameters();
            Class<?> aClass=Class.forName(className);
            Method method=aClass.getMethod(methodName,parameterTypes);
            String beanName=className.substring(className.lastIndexOf(".")+1);

            Object bean= RpcContext.getBean(beanName);
            Object invoke=method.invoke(bean,parameters);

            ctx.writeAndFlush(invoke);


        }
    }
}
